package com.xgkj.diyiketang.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.http.engine.TaskEventListener;
import com.xgkj.diyiketang.task.CreateYuanwangTask;
import com.xgkj.diyiketang.util.DateTimePickDialogUtil;
import com.xgkj.diyiketang.util.ImageCache;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.weidget.RoundImageView;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CreateYuanwangActivity extends BaseActivity implements View.OnClickListener{
    private Context mContext;
    private RelativeLayout titleLayout;
    private TextView back;
    private RelativeLayout yuanwangTypeLayout;
    private EditText yuanwangTypeEdit;
    private RelativeLayout yuanwangStarttimeLayout;
    private TextView yuanwangStarttime;
    private RelativeLayout yuanwangEndtimeLayout;
    private TextView yuanwangEndtime;
    private RelativeLayout jianzhengLayout;
    private TextView jianzhengText;
    private TextView rightCi;
    private RelativeLayout jiesuoFlowerLayout;
    private TextView jiesuoFlowerText;
    private TextView rightDuo;
    private LinearLayout jianzhengrenLayout;
    private ImageView addJianzhengren;
    private EditText yuanwanDescEdit;
    private EditText startTimeEdit;
    private EditText endTimeEdit;
    private EditText jianzhengNumEdit;
    private EditText jiesuoFlowerEdit;
    private Button createBtn;
    private PopupWindow yuanwangTypePop;
    private SimpleDateFormat df;
    private String yuanwangTitle;
    private String yuanwangDesc;
    private String startTime;
    private String endTime;
    private String jianzhengNum;
    private String jiesuoFlowerNum;
    private String jianzhengren;
    private List<String> jianzhengrenList = new ArrayList<>();
    private int mTaskId = -1;
    private EatShowUserInfo mUserInfo;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_yuanwang);
        mContext = this;
        initView();
        df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        mUserInfo = getEatShowApp().getmUserInfo();
    }

    private void initView(){
        back = (TextView) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        yuanwangTypeLayout = (RelativeLayout) findViewById(R.id.yuanwang_type_layout);
        yuanwangTypeEdit = (EditText) findViewById(R.id.yuanwang_title_edit);

        yuanwanDescEdit = (EditText) findViewById(R.id.yuanwang_desc_edit);

        yuanwangStarttimeLayout = (RelativeLayout) findViewById(R.id.yuanwang_starttime_layout);
        yuanwangStarttime = (TextView) findViewById(R.id.yuanwang_starttime);
        startTimeEdit =  (EditText) findViewById(R.id.starttime_edit);
        yuanwangStarttimeLayout.setOnClickListener(this);

        yuanwangEndtimeLayout = (RelativeLayout) findViewById(R.id.yuanwang_endtime_layout);
        yuanwangEndtime = (TextView) findViewById(R.id.yuanwang_endtime);
        endTimeEdit = (EditText) findViewById(R.id.endtime_edit);
        yuanwangEndtimeLayout.setOnClickListener(this);

        jianzhengLayout = (RelativeLayout) findViewById(R.id.jianzheng_layout);
        jianzhengText = (TextView) findViewById(R.id.jianzheng_text);
        jianzhengNumEdit = (EditText) findViewById(R.id.jianzheng_edit);
        rightCi = (TextView) findViewById(R.id.right_ci);
        jiesuoFlowerLayout = (RelativeLayout) findViewById(R.id.jiesuo_flower_layout);

        jiesuoFlowerText = (TextView) findViewById(R.id.jiesuo_flower_text);
        rightDuo = (TextView) findViewById(R.id.right_duo);
        jiesuoFlowerEdit = (EditText) findViewById(R.id.jiesuo_flower_edit);

        jianzhengrenLayout = (LinearLayout) findViewById(R.id.jianzhengren_layout);
        addJianzhengren = (ImageView) findViewById(R.id.add_jianzhengren);
        addJianzhengren.setOnClickListener(this);

        createBtn = (Button) findViewById(R.id.create_yuanwang_btn);
        createBtn.setOnClickListener(this);
        initTypePopWindow();

    }

    private void initTypePopWindow() {

    }

    private void createYuanwang(){
        CreateYuanwangTask task = new CreateYuanwangTask(yuanwangTitle,yuanwangDesc,startTime,endTime,jianzhengNum,jiesuoFlowerNum,jianzhengren);
        task.addListener(mListener);
        mTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private TaskEventListener mListener = new ShowToastTaskEventListener(this){
        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (mTaskId == taskId){
                mTaskId = -1;
                ToastUtil.showMessage(mContext,R.string.yuanwang_create_success);
                setResult(RESULT_OK);
                finish();
            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            mTaskId = -1;
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.create_yuanwang_btn:
                if (checkInput()){
                    createYuanwang();
                }
                break;

            case R.id.yuanwang_starttime_layout:
                String initTime = df.format(new Date());
                DateTimePickDialogUtil dateTimePickDialogUtil = new DateTimePickDialogUtil(CreateYuanwangActivity.this,initTime);
                dateTimePickDialogUtil.dateTimePicKDialog(startTimeEdit);
                break;
            case R.id.yuanwang_endtime_layout:
                String initEndTime = df.format(new Date());
                DateTimePickDialogUtil dateTimePickDialog = new DateTimePickDialogUtil(CreateYuanwangActivity.this,initEndTime);
                dateTimePickDialog.dateTimePicKDialog(endTimeEdit);
                break;
            case R.id.add_jianzhengren:
//                Intent intent = new Intent(mContext,SearchChiBanActivity.class);
//                intent.putExtra("From",1);
//                startActivityForResult(intent,100);
                Intent intent1 = new Intent(mContext,ChooseJianzhengrenActivity.class);
                startActivityForResult(intent1,100);

                break;
        }
    }

    private boolean checkInput(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        yuanwangTitle = yuanwangTypeEdit.getText().toString();
        if (ViewUtil.isNull(yuanwangTitle)){
            ToastUtil.showMessage(mContext,R.string.yuanwang_no_title);
            return false;
        }
        yuanwangDesc = yuanwanDescEdit.getText().toString();
        if (ViewUtil.isNull(yuanwangDesc)){
            ToastUtil.showMessage(mContext,R.string.yuanwang_no_desc);
            return false;
        }

        startTime = startTimeEdit.getText().toString();
        endTime = endTimeEdit.getText().toString();
        if (ViewUtil.isNull(startTime)){
            ToastUtil.showMessage(mContext,R.string.starttime_empty);
            return false;
        }

        if (ViewUtil.isNull(endTime)){
            ToastUtil.showMessage(mContext,R.string.endtime_empty);
            return false;
        }
        Date kaishiDate = new Date();
        Date jiesuDate = new Date();
        try {
            kaishiDate = sdf.parse(startTime);
            jiesuDate = sdf.parse(endTime);
            if (jiesuDate.before(kaishiDate)){
                ToastUtil.showMessage(mContext,R.string.endtime_cannotbefore_starttime);
                return false;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        jianzhengNum = jianzhengNumEdit.getText().toString();
        if (ViewUtil.isNull(jianzhengNum)){
            ToastUtil.showMessage(mContext,R.string.yuanwang_jianzheng_empty);
            return false;
        }
        jiesuoFlowerNum = jiesuoFlowerEdit.getText().toString();
        if (ViewUtil.isNull(jiesuoFlowerNum)){
            ToastUtil.showMessage(mContext,R.string.jiesuo_flower_empty);
            return false;
        }

        jianzhengren = getJianzhengrenString();
        if(ViewUtil.isNull(jianzhengren)){
            ToastUtil.showMessage(mContext,R.string.jianzhengren_empty);
            return false;
        }


        return true;
    }

    private String getJianzhengrenString(){
        int length = jianzhengrenList.size();
        String jianzhengren = "";
        if (length>0){
            for (int i=0;i<length;i++){
                jianzhengren +=jianzhengrenList.get(i);
                jianzhengren +=";";
            }
        }

        if (!ViewUtil.isNull(jianzhengren)){
            jianzhengren = jianzhengren.substring(0,jianzhengren.length()-1);
        }

        return jianzhengren;
    }

    private void addJianzhengren(final EatShowUserInfo info){
        if (mUserInfo != null && info.getUserId().equals(mUserInfo.getUserId())){
            ToastUtil.showMessage(mContext,R.string.can_not_jianzheng_ziji);
            return;
        }
        if (jianzhengrenList.contains(info.getUserId())){
            ToastUtil.showMessage(mContext,R.string.can_not_repeat_same);
            return;
        }
        if (ViewUtil.isNull(info.getUserId())){
            return;
        }
        jianzhengrenList.add(info.getUserId());
        if (jianzhengrenList.size()>0){
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) addJianzhengren.getLayoutParams();
            params.weight = 1;
            addJianzhengren.setLayoutParams(params);
        }
        if (jianzhengrenList.size()==3){
            addJianzhengren.setVisibility(View.GONE);
        }
        final RelativeLayout jianzheng_layout = (RelativeLayout) LayoutInflater.from(mContext).inflate(R.layout.jianzhengren_layout,jianzhengrenLayout,false);
        RoundImageView head_img = (RoundImageView) jianzheng_layout.findViewById(R.id.head_image);
        ImageButton clear_btn = (ImageButton) jianzheng_layout.findViewById(R.id.clear_btn);
        TextView nickNameText = (TextView) jianzheng_layout.findViewById(R.id.nickname);
        String url = info.getUserLogo();
        if (url != null && url.length() >0 ){
            ViewUtil.Size size = new ViewUtil.Size(ViewUtil.dip2px(mContext,40),ViewUtil.dip2px(mContext,40));
            ImageCache.getInstance(mContext).loadBitmapToView(head_img,url,size);
        }
        try {
            String nick = URLDecoder.decode(info.getNickName(),"utf-8");
            nickNameText.setText(nick);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        clear_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jianzhengrenList.remove(info.getUserId());
                jianzhengrenLayout.removeView(jianzheng_layout);
                if (jianzhengrenList.size()<3 && addJianzhengren.getVisibility() == View.GONE){
                    addJianzhengren.setVisibility(View.VISIBLE);
                }

                if (jianzhengrenList.size() == 0){
                    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) addJianzhengren.getLayoutParams();
                    params.weight = 0;
                    addJianzhengren.setLayoutParams(params);
                }
            }
        });

        jianzhengrenLayout.addView(jianzheng_layout,0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null){
            Bundle bundle = data.getExtras();
            EatShowUserInfo info = (EatShowUserInfo) bundle.getSerializable("user");
            if (info != null){
                addJianzhengren(info);
            }
        }
    }
}
